package baoxin.com.robotcoach.java;

import android.content.Context;
import android.util.Log;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import baoxin.com.robotcoach.R;
import baoxin.com.robotcoach.bean.StepTx;
import baoxin.com.robotcoach.interfaces.GearObserver;
import baoxin.com.robotcoach.interfaces.Verifier;
import baoxin.com.robotcoach.utils.MyLog;

/**
 * 档位练习验证
 */
public class GearVerifier implements Verifier {
    private int index;
    private List<StepTx> stepTxList;//步骤文本
    private String[] signals;//对应蓝牙信号

    private String signal;//接受的蓝牙信号

    private long lastExc;//最后一次来的信号的时间
    private TimerTask task;

    private Context context;
    private GearObserver observer;

    public GearVerifier(Context context, GearObserver observer) {
        this.context = context;
        this.observer = observer;

        initData();
    }


    public void filterSignal(final String signal) {
        this.signal = signal;
        if (System.currentTimeMillis() - lastExc > 100) {
            excLastSignal();
        } else {
            if (task != null) {
                task.cancel();
            }
            excLastSignal();
        }
        lastExc = System.currentTimeMillis();
    }


    public void excLastSignal() {
        Timer timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                verifySignal();
            }
        };
        timer.schedule(task, 100);
    }

    public void verifySignal() {
        MyLog.w("junjie", "signal = " + signal + ",  signal[" + index + "] = " + cut(signals[index]));
        if (cut(signal).equals(cut(signals[index]))) {
            index++;
            if (index == signals.length) {
                observer.operationCorrect(index, true);
                index = 0;

            } else {
                observer.operationCorrect(index, false);
            }
        } else {
            observer.operationWrong();
            index = 0;
        }

    }

    public String cut(String signal) {
        int len = signal.length();
        return signal.substring(len - 6, len - 4);
    }

    public List<StepTx> getStepTxList() {
        return stepTxList;
    }

    public int getIndex() {
        return index;
    }

    private void initData() {
        signals = context.getResources().getStringArray(R.array.gear_practise_signal);
        String[] practiseStep = context.getResources().getStringArray(R.array.gear_practise);
        stepTxList = new ArrayList<>();
        for (String s : practiseStep) {
            StepTx stepTx = new StepTx(s);
            stepTxList.add(stepTx);
        }
        //辅助数据
        for (int i = 0; i < 9; i++) {
            StepTx stepTx = new StepTx("");
            stepTxList.add(stepTx);
        }
    }
}
